package com.feityz.handler.ptws;

import cn.hutool.core.collection.CollectionUtil;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.handler.NodeEventHandler;
import com.bstek.uflo.process.node.Node;
import com.bstek.uflo.service.ProcessService;
import com.bstek.uflo.service.TaskOpinion;
import com.bstek.uflo.service.TaskService;
import com.feityz.system.dao.ProcessIncetanceMapper;
import com.feityz.system.entity.ProcessIncetanceVo;
import com.feityz.system.service.IProcessIncetanceService;
import com.feityz.system.vo.CurrentNodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Component("ptwEndHandler")
public class PtwEndHandler implements NodeEventHandler {

    @Autowired
    private ProcessService processService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IProcessIncetanceService processIncetanceService;
    @Autowired
    private ProcessIncetanceMapper processIncetanceMapper;
    @Override
    public String desc() {
        return "PTW结束事件";
    }

    @Override
    public void enter(Node node, ProcessInstance processInstance, Context context) {

    }

    @Transactional
    @Override
    public void leave(Node node, ProcessInstance processInstance, Context context) {
        Object otherCode = processService.getProcessVariable("otherCode", processInstance);

        if(otherCode != null){

            String codes[] = otherCode.toString().split(",");
            for (String bizId : codes) {
                ProcessIncetanceVo processIncetanceVo = processIncetanceMapper.selectCurrentInstance(bizId);
                if(processIncetanceVo!=null){
                    ProcessInstance instance = processService.getProcessInstanceById(processIncetanceVo.getProcessInstanceId());

                    if(instance!=null) {

                        List<CurrentNodeVo> current = processIncetanceService.getCurrent(instance.getId());

                        if (CollectionUtil.isNotEmpty(current)) {

                            String url = current.get(0).getUrl();

                            if ("5".equals(url)) {
                                taskService.forward(current.get(0).getTaksId(), "签结", new TaskOpinion("PTW签结", "签结"));
                            } else if ("4".equals(url)) {
                                taskService.forward(current.get(0).getTaksId(), "作废", new TaskOpinion("PTW作废", "作废"));
                            } else if ("2".equals(url)) {
                                taskService.forward(current.get(0).getTaksId(), "作废", new TaskOpinion("PTW作废", "作废"));
                            }

                        }
                    }
                }
            }

        }
    }
}
